// src/composables/useEditStation.js

import {ref, reactive} from 'vue';
import axios from 'axios';
import {ElMessage} from 'element-plus';

export function useEditStation() {
    // 编辑/查看弹窗
    const editDialogVisible = ref(false);
    const viewDialogVisible = ref(false);

    // 编辑表单
    const editForm = reactive({
        id: null,
        stationName: '',
        stationCode: '',
        stationType: '',
        stationProperty: '',
        enableEvaluation: 1,
        openTime: null,
        closeTime: null,
        address: '',
        stationIntro: '',
        stationImgUrl: '',
        createTime: '',
        status: '正常',
        chargingPileCount: 0,
        chargingPiles: [],
    });

    // 查看表单
    const viewForm = reactive({
        stationName: '',
        stationCode: '',
        stationType: '',
        stationProperty: '',
        enableEvaluation: 1,
        openTime: null,
        closeTime: null,
        address: '',
        stationIntro: '',
        stationImgUrl: '',
        createTime: '',
        status: '正常',
        chargingPileCount: 0,
        chargingPiles: [],
    });

    // 打开编辑弹窗
    const editStation = async (row) => {
        try {
            const response = await axios.get(`/station/getStationById/${row.id}`);
            const {station: stationData, chargingPiles} = response.data;
            Object.assign(editForm, stationData);
            editForm.chargingPiles = chargingPiles || [];
            editDialogVisible.value = true;
        } catch (error) {
            console.error('加载站点数据失败', error);
            ElMessage.error('加载站点数据失败');
        }
    };

    // 打开查看弹窗
    const viewStation = async (row) => {
        try {
            const res = await axios.get(`/station/getStationById/${row.id}`);
            console.log('API 响应:', res);
            const {station: stationData, chargingPiles} = res.data;
            // 打印解析后的 station 和 chargingPiles 数据
            console.log('解析的 station 数据:', res.data.station);
            console.log('解析的 chargingPiles 数据:', chargingPiles);
            Object.assign(viewForm, stationData);
            viewForm.chargingPiles = chargingPiles || [];
            viewDialogVisible.value = true;
        } catch (error) {
            console.error('查看站点失败', error);
            ElMessage.error('查看站点失败');
        }
    };

    return {
        editDialogVisible,
        viewDialogVisible,
        editForm,
        viewForm,
        editStation,
        viewStation,
    };
}
